/* 
* Copyright (c) 2021-2023 Alibaba Cloud Computing Ltd. 
* SPDX-License-Identifier: MulanPSL-2.0 
*/ 
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Button, Tooltip, Space, Popconfirm } from 'antd';
import { DeleteOutlined, CopyOutlined, FormOutlined, UndoOutlined, HighlightOutlined,
  CaretRightFilled, CaretDownFilled } from '@ant-design/icons';
import { FormattedMessage, useIntl } from '@umijs/max';
import type { ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
//
import PageContainer from '@/components/public/PageContainer';
import PopoverEllipsis from '@/components/public/PopoverEllipsis';
import LogModal from '@/pages/List/LogModal'
import SetModal from './Set'
import CreateModal from './Create'
import Count from './Count'
import { handleRes, statusEnum, viewDetails } from '@/uitls/uitls'
import { getRequestData } from './service'
import { resetTableData } from './dataDealWith'
import styles from './index.less';

// 允许编辑的项
const defaultName = ['custom']

export type TableListItem = {
  id: string;
  name: string;
  status: string;
  involved: boolean,
  count: any,
};

/**
 * 静态调优列表
 */
export default () => {
  const { formatMessage } = useIntl();
  const [loading, setLoading] = useState(false)
  const [dataSource, setDataSource] = useState<any>([])
  const [expandedRowKeys, setExpandedRowKeys] = useState<any>([])
  const setModalRef: any = useRef(null)
  // const createModalRef: any = useRef(null)
  const [createModalState, setCreateModalState] = useState<any>({
    title: '',
    row: null,
  })
  const logModalRef: any = useRef(null)

  // 初始化请求数据
  const requestAllData = async ()=> {
    setLoading(true);
    try {
      const data = await getRequestData({ cmd: 'keentune profile list'}) || {}
      const resetData = resetTableData(data.msg)
      if (resetData && resetData.length) {
        setDataSource(resetData)
        setExpandedRowKeys( resetData.filter((item: any)=> item.involved).map((item: any)=> item.id) )
      } else {
        setDataSource([]);
        setExpandedRowKeys([])
      }
      setLoading(false);
    } catch (err) {
      setLoading(false);
    }
  }

  useEffect(()=> {
    requestAllData()
    return ()=> {
      setLoading(false)
      setDataSource([])
    }
  }, [])

  // 操作功能
  const cmdOperation = async (q: any, operateType: string)=> {
    setLoading(true);
    try {
      const res = await getRequestData(q) || {}
      setLoading(false);
      if (res.suc) {
        requestAllData()
      } 
      handleRes(res, formatMessage({ id: operateType }))
    } catch (err) { 
      setLoading(false);
    }
  }

  const fn = (key: string, row: any)=> {
    switch (key) {
      case 'set': setModalRef.current?.show({ title: '设置调优项', url: '', row }); break
      case 'copy': setCreateModalState({ title: key, row }); break // createModalRef.current?.show({ title: key, row }); break
      case 'edit': setCreateModalState({ title: key, row }); break // createModalRef.current?.show({ title: key, row }); break
      case 'rollback': cmdOperation({ cmd: 'keentune profile rollback'}, key); break
      case 'delete': cmdOperation({ cmd: `keentune profile delete --name ${row.parentName}/${row.name}`}, key); break
      default: null
    }
  }

  const columns: ProColumns<TableListItem>[] = [
    {
      title: 'Profile Set',
      dataIndex: 'name',
    },
    {
      title: 'Contains Active?',
      dataIndex: 'involved',
      render: (text: any, record: any) => {
        return <span style={record.involved ? {color:'#ff4d4f',fontWeight: 600}: {}}>{record.involved ? 'Yes': 'No'}</span>
      },
    },
    {
      title: 'Profile Count',
      dataIndex: 'count',
    },
  ];

  const childColumns = [
    {
      title: 'Profile Name',
      dataIndex: 'name',
      width: 300,
      render: (text: any, row: any) => {
        const api = row.parentName === 'custom'? `/var/keentune/profile/${row.name}`: `/etc/keentune/profile/${row.parentName}/${row.name}`
        return <PopoverEllipsis title={text} onClick={()=> logModalRef?.current?.show({ title: 'Details', url: api })} />
      },
    },
    {
      title: 'Status',
      dataIndex: 'status',
      valueEnum: statusEnum,
      width: 280,
    },
    {
      title: 'Target Group',
      dataIndex: 'target',
      render: (text, record) => <span><Count record={record} minWidth={50}/></span>,
    },
    {
      title: <FormattedMessage id="operations" />,
      key: 'option',
      width: 230,
      valueType: 'option',
      render: (text, record, _, action) => {
        const iconStyle = { fontSize:16,color:'#008dff' }
        const disableStyle = { fontSize:16,color:'#ccc' }
        return (
          <Space size={24}>
            {defaultName.includes(record.parentName)?
              <Popconfirm
                title={ formatMessage({ id: 'confirm.content' }) }
                onConfirm={()=> fn('delete', record)}
                onCancel={()=>{}}
                okText={formatMessage({ id: 'btn.yes' }) }
                cancelText={formatMessage({ id: 'btn.no' }) }
              >
                <Tooltip placement="top" title={ formatMessage({ id: 'delete' }) }>
                  <DeleteOutlined style={{ fontSize:16, }}/>
                </Tooltip>
              </Popconfirm>
              : <DeleteOutlined style={disableStyle}/>
            }

            <Tooltip placement="top" title={ formatMessage({ id: 'copy' }) }>
              <CopyOutlined onClick={()=> fn('copy', record)} style={iconStyle}/>
            </Tooltip>

            {defaultName.includes(record.parentName)?
              <Tooltip placement="top" title={ formatMessage({ id: 'edit' }) }>
                <FormOutlined onClick={()=> fn('edit', record)} style={iconStyle}/>
              </Tooltip>
              : <FormOutlined style={disableStyle}/> }
            
            {record.status === 'active'?
              <Tooltip placement="top" title={ formatMessage({ id: 'rollback', defaultMessage: 'Rollback' }) }>
                <UndoOutlined onClick={()=> fn('rollback', record)} style={iconStyle}/>
              </Tooltip>
            : <UndoOutlined style={disableStyle}/> }
            
            <Tooltip placement="top" title={ formatMessage({ id: 'set' }) }>
              <HighlightOutlined onClick={()=> fn('set', record)} style={iconStyle}/>
            </Tooltip>
          </Space>
        )
      }
    },
  ];

  return (
    <div className={styles.static_page}>
      <PageContainer style={{ marginTop: 24,padding: 0 }}>
        <ProTable
          className={styles.ProTable}
          loading={loading}
          headerTitle={<FormattedMessage id="pages.profileList.title" />}
          options={{
            reload: requestAllData,
            setting: true,
            density: false,
          }}
          size="small"
          rowKey="id"
          columns={columns}
          dataSource={dataSource}
          expandable={{
            // defaultExpandAllRows: true,
            expandedRowKeys: expandedRowKeys,
            expandedRowRender: (record: any) => {
              const tempDataSource = record?.childDataSource?.map((item: any)=> ({ ...item, parentName: record.name })) || []
              return (
                <div className={styles.child_ProTable}>
                  <ProTable rowKey="id" size="small" columns={childColumns} dataSource={tempDataSource}
                    headerTitle={false}
                    search={false}
                    options={false}
                    pagination={false} 
                  />
                </div>
              )
            },
            onExpand: (_, record) => _ ? setExpandedRowKeys(expandedRowKeys.concat([record.id])) : setExpandedRowKeys(expandedRowKeys.filter((item: any)=> item !== record.id)),
            expandIcon: ({ expanded, onExpand, record }: any) => 
              (expanded? <CaretDownFilled onClick={e => onExpand(record, e)} /> :
              <CaretRightFilled onClick={e => onExpand(record, e)} />),
          }}
          pagination={false}
          search={false}
          dateFormatter="string"
          toolBarRender={() => [
            <Button key="button" type="primary" onClick={
              ()=> setCreateModalState({ title: 'create', row: null }) // createModalRef.current?.show({ title: 'create' })
            }>
              <FormattedMessage id="create" />
            </Button>,
          ]}
        />
        <SetModal ref={setModalRef} callback={requestAllData} />

        {/* Create */}
        <CreateModal {...createModalState} dataSource={dataSource} 
          callback={useCallback((info: any) => {
            // console.log(info)
            setCreateModalState({ title: '', row: null })
            if (info.data === 'refresh') requestAllData()
          }, [])}
          defaultName={defaultName} />

        {/* details */}
        <LogModal ref={logModalRef} /> 
      </PageContainer>
    </div>
  );
};